package com.uwantsoft.business.infrastructure.repository.querier;

import com.uwantsoft.business.facade.dto.user.UserOverviewQueryCondition;
import com.uwantsoft.business.service.domain.user.User;
import com.uwantsoft.util.paging.AbstractQuerier;
import com.uwantsoft.util.paging.ParameterFilter;
import org.hibernate.Query;

import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.util.StringUtils;

/**
 * @author peichen
 */
public class UserOverviewQuerier extends AbstractQuerier<User> {
    private UserOverviewQueryCondition userOverviewQueryCondition;


    public UserOverviewQuerier(HibernateTemplate hibernateTemplate, UserOverviewQueryCondition userOverviewQueryCondition) {
        super(hibernateTemplate);
        this.userOverviewQueryCondition = userOverviewQueryCondition;
        addUserNameFilter();
    }

    private void addUserNameFilter() {
        final String name = userOverviewQueryCondition.getName();
        if (StringUtils.hasText(name)) {
            addFilter(new ParameterFilter() {
                @Override
                public void setParameter(Query query) {
                    query.setParameter("name", "%"+name+"%");
                }

                @Override
                public String getSubHql() {
                    return "and u.name like :name";
                }
            });
        }
    }

    @Override
    public int getStartPosition() {
        return userOverviewQueryCondition.getStartIndex();
    }

    @Override
    public int getItemsAmountPerPage() {
        return userOverviewQueryCondition.getObjectsPerPage();
    }

    @Override
    public String getResultHql() {
        return "from User u where u.active=true " + getSubHql();
    }

    @Override
    public String getAmountHql() {
        return "select count(*) from User u where u.active=true " + getSubHql();
    }
}
